package com.huanshi.module.oms.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.huanshi.common.CommonResult;
import com.huanshi.entity.OmsCart;
import com.huanshi.service.OmsCartService;
import com.huanshi.utils.JwtTokenUtil;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 幻世
 * @since 2023-10-09
 */
@RestController
@RequestMapping("/api/oms/cart")
public class OmsCartController {

    @Resource
    private OmsCartService omsCartService;



    @PostMapping("/add")
    public CommonResult add(@RequestBody OmsCart omsCart) {
        omsCart.setCreateDate(LocalDateTime.now());
        omsCart.setModifyDate(LocalDateTime.now());
        return CommonResult.success(omsCartService.save(omsCart));
    }

    @PostMapping("/update")
    public CommonResult update(@RequestBody OmsCart omsCart) {
        omsCart.setModifyDate(LocalDateTime.now());
        return CommonResult.success(omsCartService.saveOrUpdate(omsCart));
    }

    @DeleteMapping("/{id}")
    public CommonResult delete(@PathVariable Integer id) {
        return CommonResult.success(omsCartService.removeById(id));
    }

    @PostMapping("/del/batch")
    public CommonResult deleteBatch(@RequestBody List<Integer> ids) {
        return CommonResult.success(omsCartService.removeByIds(ids));
    }

    @GetMapping("/list")
    public CommonResult findUserCart(@RequestParam(value = "id", defaultValue = "0") Integer userId) {
        return CommonResult.success(omsCartService.getCartListByUserId(userId));
    }
    @GetMapping("/list/user")
    public CommonResult findCartByToken(@RequestParam("token") String token) {
        Integer userId = JwtTokenUtil.getUserId(token);
        return CommonResult.success(omsCartService.getCartListByUserId(userId));
    }

    @GetMapping("/check")
    public CommonResult checkCart(
            @RequestParam("productId") Integer productId,
            @RequestParam("userId") Integer userId) {
        return CommonResult.success(omsCartService.checkCart(productId, userId));
    }
    @GetMapping
    public CommonResult findAll() {
        return CommonResult.success(omsCartService.list());
    }

    @GetMapping("/{id}")
    public CommonResult findOne(@PathVariable Integer id) {
        return CommonResult.success(omsCartService.getById(id));
    }

    @GetMapping("/page")
    public CommonResult findPage(@RequestParam Integer pageNum,
                                @RequestParam Integer pageSize) {
        QueryWrapper<OmsCart> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("id");
        return CommonResult.success(omsCartService.page(new Page<>(pageNum, pageSize), queryWrapper));
    }

}

